//
//  EnumerationsExample.swift
//  SwiftCode
//
//  Created by yuhus on 2023/10/11.
//

import Foundation

/// 枚举
class EnumerationsExample: ListViewController {
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "递归枚举", description: "成员使用该枚举类型的实例作为关联值", action: recursiveEnum),
  ]
}

/// 算术表达式
private indirect enum ArithmeticExpression {
  /// 数字
  case number(Int)
  /// 相加
  case addition(ArithmeticExpression, ArithmeticExpression)
  /// 相乘
  case multiplication(ArithmeticExpression, ArithmeticExpression)
}

private func evaluate(_ expression: ArithmeticExpression) -> Int {
  switch expression {
  case let .number(value):
    return value
  case let .addition(left, right):
    return evaluate(left) + evaluate(right)
  case let .multiplication(left, right):
    return evaluate(left) * evaluate(right)
  }
}

private func recursiveEnum() {
  // 表达式 (5 + 4) * 2
  let five = ArithmeticExpression.number(5)
  let four = ArithmeticExpression.number(4)
  let sum = ArithmeticExpression.addition(five, four)
  let product = ArithmeticExpression.multiplication(sum, .number(2))
  
  print(evaluate(product))
  // 打印"18"
}
